using System;
using System.IO;
using System.Threading.Tasks;
using CR.ErrorCode;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CR.API.Controllers
{
    /// <summary>
    /// 文件上传控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<FileUploadController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="environment">Web环境</param>
        /// <param name="logger">日志记录器</param>
        public FileUploadController(IWebHostEnvironment environment, ILogger<FileUploadController> logger)
        {
            _environment = environment;
            _logger = logger;
        }

        /// <summary>
        /// 上传图片文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns>上传结果</returns>
        [HttpPost("image")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            try
            {
                // 验证文件
                if (file == null || file.Length == 0)
                {
                    return BadRequest(ApiResult<object>.Error("没有提供文件"));
                }

                // 验证文件类型
                var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/gif" };
                if (!Array.Exists(allowedTypes, type => type == file.ContentType))
                {
                    return BadRequest(ApiResult<object>.Error("仅支持JPEG, JPG, PNG和GIF格式图片"));
                }

                // 验证文件大小（限制为5MB）
                if (file.Length > 5 * 1024 * 1024)
                {
                    return BadRequest(ApiResult<object>.Error("文件大小不能超过5MB"));
                }

                // 创建上传目录
                string uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads", "images");
                
                // 确保目录存在
                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                // 生成唯一文件名
                string uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(file.FileName);
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                // 保存文件
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }

                // 返回文件URL
                string fileUrl = $"{Request.Scheme}://{Request.Host}/uploads/images/{uniqueFileName}";

                return Ok(ApiResult<object>.Ok(new { url = fileUrl }, "图片上传成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传图片时出错");
                return StatusCode(500, ApiResult<object>.Error($"上传图片失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除上传的图片
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>删除结果</returns>
        [HttpDelete("image/{fileName}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public IActionResult DeleteImage(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    return BadRequest(ApiResult.Error("文件名不能为空"));
                }

                // 安全检查：防止目录遍历攻击
                if (fileName.Contains("..") || fileName.Contains("/") || fileName.Contains("\\"))
                {
                    return BadRequest(ApiResult.Error("无效的文件名"));
                }

                string uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads", "images");
                string filePath = Path.Combine(uploadsFolder, fileName);

                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound(ApiResult.Error("文件不存在", ApiEnums.NotFound));
                }

                System.IO.File.Delete(filePath);
                return Ok(ApiResult.Ok(null, "图片删除成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除图片时出错");
                return StatusCode(500, ApiResult.Error($"删除图片失败: {ex.Message}"));
            }
        }
    }
} 